package com.googlecode.flealancemarket.tapestry.pages.inbox;

import com.googlecode.flealancemarket.core.tapestry.SpringBean;
import com.googlecode.flealancemarket.metamodel.PrivateMessage;
import com.googlecode.flealancemarket.service.commands.ChangeMessageRead;
import com.googlecode.flealancemarket.service.commands.DeleteMessage;
import com.googlecode.flealancemarket.service.commands.GetPrivateMessageById;
import java.text.Format;
import java.text.SimpleDateFormat;
import org.apache.tapestry.annotations.InjectPage;
import org.apache.tapestry.annotations.OnEvent;
import org.apache.tapestry.annotations.Persist;
import org.apache.tapestry.ioc.annotations.Inject;

public class Message extends AbstractInboxPage {

    @Inject
    @SpringBean("com.googlecode.flealancemarket.service.commands.GetPrivateMessageById")
    private GetPrivateMessageById getPrivateMessageById;

    @Inject
    @SpringBean("com.googlecode.flealancemarket.service.commands.ChangeMessageRead")
    private ChangeMessageRead changeMessageRead;

    @Inject
    @SpringBean("com.googlecode.flealancemarket.service.commands.DeleteMessage")
    private DeleteMessage deleteMessage;

    @Persist
    private PrivateMessage message;

    @InjectPage
    private New newMessage;
    
    Object onActivate(Long id){

        getPrivateMessageById.setId(id);
        PrivateMessage pm = getPrivateMessageById.execute();
        if(pm==null || !( ((Long)pm.getSender().get_id()).equals(getSession().getUserId()) || ((Long)pm.getReceiver().get_id()).equals(getSession().getUserId()) )) {
            getSession().setMessage("There's no such a message");
            return Index.class;
        }
        message = pm;
        if(!message.getRead() && userIsReceiver()){
            changeMessageRead.setMessage(message);
            changeMessageRead.setRead(true);
            changeMessageRead.execute();
        }

        return super.onActivate();
    }

    public boolean userIsReceiver(){
        return getUser().equals(message.getReceiver());
    }

    public PrivateMessage getMessage() {
        return message;
    }

    public void setMessage(PrivateMessage message) {
        this.message = message;
    }
    
    private final String format = "dd.MM.yyyy";

    public Format getFormat() {
        return new SimpleDateFormat(format);
    }

    @OnEvent(component="deleteMessage")
    Object deleteMessage(Long id){
        deleteMessage.setId(id);
        deleteMessage.execute();
        return Index.class;
    }

    @OnEvent(component="replyMessage")
    Object replyMessage(){
        newMessage.setUsername(message.getSender().getUsername());
        newMessage.setTitle("Re: " + message.getTitle());
        return newMessage;
    }
}
